package com.qp.basics.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.qp.basics.admin.repository.EntityHistoryRepository;
import com.qp.basics.admin.service.EntityHistoryService;
import com.qp.basics.admin.service.dto.EntityHistoryQueryCriteria;
import com.qp.basics.admin.service.mapstruct.EntityHistoryMapper;
import com.qp.basics.common.domain.EntityHistory;
import com.qp.basics.common.service.dto.EntityHistoryDto;
import com.qp.basics.common.utils.FileUtil;
import com.qp.basics.common.utils.PageUtil;
import com.qp.basics.common.utils.QueryHelp;

import com.qp.basics.common.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 实体修改历史
**/
@Service
@RequiredArgsConstructor
public class EntityHistoryServiceImpl implements EntityHistoryService {

    private final EntityHistoryRepository entityHistoryRepository;
    private final EntityHistoryMapper entityHistoryMapper;

    @Override
    public Map<String,Object> queryAll(EntityHistoryQueryCriteria criteria, Pageable pageable){
        Page<EntityHistory> page = entityHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(entityHistoryMapper::toDto));
    }

    @Override
    public List<EntityHistoryDto> queryAll(EntityHistoryQueryCriteria criteria){
        return entityHistoryMapper.toDto(entityHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public EntityHistoryDto findById(Long id) {
        EntityHistory entityHistory = entityHistoryRepository.findById(id).orElseGet(EntityHistory::new);
        ValidationUtil.isNull(entityHistory.getId(),"EntityHistory","id",id);
        return entityHistoryMapper.toDto(entityHistory);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EntityHistoryDto create(EntityHistory resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        return entityHistoryMapper.toDto(entityHistoryRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EntityHistory resources) {
        EntityHistory entityHistory = entityHistoryRepository.findById(resources.getId()).orElseGet(EntityHistory::new);
        ValidationUtil.isNull( entityHistory.getId(),"EntityHistory","id",resources.getId());
        resources.setId(entityHistory.getId());
        entityHistoryRepository.save(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            entityHistoryRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<EntityHistoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EntityHistoryDto entityHistory : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("实体id", entityHistory.getEntityId());
            map.put("类名", entityHistory.getEntityName());
            map.put("关键字段信息", entityHistory.getEntityTitle());
            map.put("实体内容", entityHistory.getContent());
            map.put("备注", entityHistory.getComment());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public JSONObject importExcel(MultipartFile file) {
        JSONObject res=new JSONObject();
/**
        try (InputStream is = file.getInputStream()) {
            ExcelX ex = new ExcelX(is);
            List<Map> l = ex.excelToMapList(0);
            int count=0;
            for (int i = 0; i < l.size(); i++) {
                Map m = l.get(i);
                Object t = m.get("id");
                if (t == null || "".equals(t)) {
                    continue;
                }
                EntityHistory q = new EntityHistory();
            String entityId = ImortExportUtil.toStr(m.get("实体id"));
            q.setEntityId(entityId);
            String entityName = ImortExportUtil.toStr(m.get("类名"));
            q.setEntityName(entityName);
            String entityTitle = ImortExportUtil.toStr(m.get("关键字段信息"));
            q.setEntityTitle(entityTitle);
            String content = ImortExportUtil.toStr(m.get("实体内容"));
            q.setContent(content);
            String comment = ImortExportUtil.toStr(m.get("备注"));
            q.setComment(comment);
                q = entityHistoryRepository.save(q);
                count++;
            }
            res.put("msg","导入成功：共导入"+count+"条");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("msg","导入失败："+e.getMessage());
        }
            **/
        return res;
    }
}
